// models/userModel.js
const db = require('./db');

class UserModel {
  static async register(username, password) {
    // 参数验证
    if (!username || !password) {
      throw new Error('用户名和密码不能为空');
    }
    if (username.length < 3 || password.length < 6) {
      throw new Error('用户名至少3个字符，密码至少6个字符');
    }
  
    // 检查用户名是否存在
    const [existingUser] = await db.execute(
      'SELECT * FROM user WHERE username = ?',
      [username]
    );
  
    if (existingUser.length > 0) {
      // 如果用户名已存在，返回错误信息
      return { success: false, message: '用户名已存在' };
    }
  
    try {
      // 执行数据库插入操作
      const [result] = await db.execute(
        'INSERT INTO user (username, password) VALUES (?, ?)',
        [username, password]
      );
  
      // 检查是否插入成功
      if (result.affectedRows === 0) {
        throw new Error('注册失败');
      }
      return { success: true, message: '注册成功' };
    } catch (error) {
      // 错误处理
      console.error('注册失败:', error);
      throw new Error('注册过程中发生错误');
    }
  }

  static async login(username, password) {
    console.log('Input password:', password); // 打印输入的密码
    const results = await db.execute(
      'SELECT password FROM user WHERE username = ?',
      [username]
    );
    console.log('Query results:', results); // 打印查询结果
    if (results.length === 0 || !results[0].length) {
      console.log('No user found with the given username or no password field.'); // 用户不存在或没有密码字段
      return null;
    }
    const storedPassword = results[0][0].password;
    console.log('Stored password:', storedPassword); // 打印数据库中存储的密码
    if (!storedPassword || storedPassword !== password) {
      return null;
    }
    return { username }; // 登录成功，返回用户名
  }


  static async setFirstLoginDate(username, date) {
    // 检查是否已经有首次登录日期
    const isFirstLogin = await this.isFirstLogin(username);
    if (isFirstLogin) {
      // 如果没有首次登录日期，设置首次登录日期
      const mysqlDate = date.replace('T', ' ').slice(0, 19); // 转换为 'YYYY-MM-DD HH:MM:SS' 格式
      await db.execute(
        'UPDATE user SET first_login_date = ? WHERE username = ?',
        [mysqlDate, username]
      );
      console.log(`First login date set for user ${username}: ${mysqlDate}`);
    } else {
      const query = 'SELECT first_login_date FROM user WHERE username = ?';
      console.log(`Executing query: ${query} with username: ${username}`);
      const result = await db.query(query, [username]);
      if (result.length > 0 && result[0].first_login_date !== undefined && result[0].first_login_date !== null) {
        console.log(`First login date for user ${username}: ${result[0].first_login_date}`);
      } else {
        console.log(`No first login date found for user ${username}`);
      }
    }
  }
}


module.exports = UserModel;